package com.bjbn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bjbn.entity.BmsDeviceInfo;
import com.bjbn.mapper.BmsDeviceInfoMapper;
import com.bjbn.service.BaDeviceStateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BaDeviceStateServiceImpl implements BaDeviceStateService {

    @Value("${ba.device.state.url:http://10.120.78.214:32722/ba/state}")
    private String baStateUrl;

    @Autowired
    private BmsDeviceInfoMapper deviceInfoMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String getDeviceState(String stateId) {
        try {
            // 构建请求参数
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("stateId", stateId);
            requestBody.put("position", "EAST");

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(baStateUrl, request, String.class);
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                if (responseJson.getBoolean("success")) {
                    JSONObject data = responseJson.getJSONObject("data");
                    if (data != null) {
                        JSONObject value = data.getJSONObject("Value");
                        if (value != null) {
                            return value.getString("Value");
                        }
                    }
                }
            }
            
            log.warn("BA设备状态查询失败，stateId: {}, response: {}", stateId, response.getBody());
            return null;
            
        } catch (Exception e) {
            log.error("查询BA设备状态异常，stateId: {}", stateId, e);
            return null;
        }
    }

    @Override
    public String parseDeviceState(String deviceNum) {
        try {
            // 查询设备的所有属性
            List<BmsDeviceInfo> deviceInfos = deviceInfoMapper.selectList(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BmsDeviceInfo>()
                            .eq(BmsDeviceInfo::getDeviceNum, deviceNum)
            );

            Map<String, String> stateMap = new HashMap<>();
            stateMap.put("下行", "0");
            stateMap.put("上行", "0");
            stateMap.put("故障", "0");

            // 遍历设备属性，查询每个属性的状态
            for (BmsDeviceInfo deviceInfo : deviceInfos) {
                String contactId = deviceInfo.getContactId();
                String tagName = deviceInfo.getTagName();
                
                if (contactId != null) {
                    String stateValue = getDeviceState(contactId);
                    if (stateValue != null) {
                        // 根据tag_name判断状态类型
                        if (tagName != null) {
                            if (tagName.contains("下行")) {
                                stateMap.put("下行", stateValue);
                            } else if (tagName.contains("上行")) {
                                stateMap.put("上行", stateValue);
                            } else if (tagName.contains("故障")) {
                                stateMap.put("故障", stateValue);
                            }
                        }
                    }
                }
            }

            return JSON.toJSONString(stateMap);
            
        } catch (Exception e) {
            log.error("解析设备状态异常，deviceNum: {}", deviceNum, e);
            return null;
        }
    }
} 